package cn.huijielong.modules.group.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.github.pagehelper.Page;

import cn.huijielong.common.utils.PageUtils;
import cn.huijielong.common.utils.Query;
import cn.huijielong.common.utils.RD;
import cn.huijielong.common.utils.VSUtil;
import cn.huijielong.modules.group.entity.OrderEntity;
import cn.huijielong.modules.group.entity.OrderItemEntity;
import cn.huijielong.modules.group.service.OrderService;
import cn.huijielong.modules.sys.controller.AbstractController;




/**
 * 
 * 
 * @author xys
 * @email xys@gmail.com
 * @date 2019-07-03 22:46:43
 */
@RestController
@RequestMapping("/group/order")
public class OrderController  extends AbstractController{
	@Autowired
	private OrderService orderService;
	
	/**
	 * 列表
	 */
	@RequestMapping("/list")
	@RequiresPermissions("group:order:list")
	public RD list(@RequestParam Map<String, Object> params){
		Long userId=this.getUserId();
	    logger.info("从{}发送请求，参数：{}",getHeader("referer"),params.toString());
		//查询列表数据
        Query query = Query.createRequest(params);
        query.addParam("buyUserId", userId);
        
		Page<OrderEntity> orderList = orderService.queryOrders(query);
		PageUtils pageUtil = new PageUtils(orderList, orderList.getTotal(), query.getLimit(), query.getPage());
		return RD.ok().put("page", pageUtil);
	}
	@RequestMapping("/orderLogDesc/{orderId}")
	@RequiresPermissions("group:order:list")
	public RD orderLogDesc(@PathVariable("orderId") Long orderId){
		//查询列表数据
		List<String> orderList = orderService.queryOrderLogDesc(orderId);		
		return RD.ok().setData("list", orderList);
	}
	
	
	/**
	 * 信息
	 */
	@RequestMapping("/info/{orderId}")
	@RequiresPermissions("group:order:info")
	public RD info(@PathVariable("orderId") Long orderId){
		OrderEntity order = orderService.queryObject(orderId);
		
		return RD.ok().put("order", order);
	}
	
	/**
	 * 保存
	 */
	@RequestMapping("/save")
	@RequiresPermissions("group:order:save")
	public RD save(){
		Long buyUserId=getUserId();
		if(buyUserId==null || buyUserId.longValue()==0) {
			logger.error("用户ID为0，未登录，不能操作");
			return RD.error("未登录，不能操作");
		}
		net.sf.json.JSONObject json=VSUtil.requestToJSON();
		net.sf.json.JSONObject jsonOrder=json.optJSONObject("orderInfo");
		net.sf.json.JSONArray jsonItemList=json.optJSONArray("orderItemList");
		BigDecimal payAmount=VSUtil.getDecimal(json, "payAmount");
		OrderEntity order=new OrderEntity();
		order.setBuyUserId(buyUserId);
		order.setGroupId(jsonOrder.optLong("groupId"));
		order.setMerchantId(jsonOrder.optLong("merchantId"));
		order.setPayAmount(payAmount);
		if(jsonOrder.containsKey("orderId")) {
			order.setOrderId(jsonOrder.optLong("orderId"));
		}
		
		List<OrderItemEntity> itemList=new ArrayList<>();
		for(int i=0;i<jsonItemList.size();i++) {
			net.sf.json.JSONObject jsonGoods=jsonItemList.getJSONObject(i);
			OrderItemEntity orderItem=new OrderItemEntity();
			orderItem.setGoodsId(jsonGoods.optLong("goodsId"));
			orderItem.setGoodsName(jsonGoods.optString("name"));
			int buyNum=jsonGoods.optInt("buyNum");
			BigDecimal price=VSUtil.getDecimal(jsonGoods, "price");
			BigDecimal itemAmount=price.multiply(new BigDecimal(buyNum));
			orderItem.setBuyNum(buyNum);
			orderItem.setPayAmount(itemAmount);
			itemList.add(orderItem);
		}
		order.setOrderItemList(itemList);
		if(order.getOrderId()==null)
			orderService.save(order);
		else
			orderService.update(order);
		
		return RD.ok();
	}
	
	/**
	 * 修改
	 */
	@RequestMapping("/updateStatus")
	@RequiresPermissions("group:order:update")
	public RD update(){
		Query q=Query.createRequest();
		q.addParam("userId", this.getUserId());
		orderService.updateStatus(q);
		return RD.ok();
	}
	
	
	/**
	 * 删除
	 */
	@RequestMapping("/delete/{orderId}")
	@RequiresPermissions("group:order:delete")
	public RD delete(@PathVariable("orderId") Long orderId){
		Query q=Query.empty();
		q.addParam("userId", this.getUserId());
		q.addParam("orderId", orderId);
		q.addParam("newStatus", "4");
		orderService.updateStatus(q);
		return RD.ok();
	}
	
}
